package cn.signalpha.modules.base.service;

import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.base.entity.WxReplyRule;
import cn.signalpha.modules.base.mapper.WxReplyRuleMapper;
import cn.signalpha.modules.base.vo.WxReplyRuleVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 服务类
 *
 * @author signalpha
 */
@Slf4j
@Service
public class WxReplyRuleService extends ServiceImpl<WxReplyRuleMapper, WxReplyRule> {

	private WxMpService wxMpService;

	@Autowired
	public WxReplyRuleService(@Lazy WxMpService wxMpService){
		this.wxMpService = wxMpService;

	}

	/**
	 * 自定义分页
	 */
    public IPage<WxReplyRuleVO> selectWxReplyRulePage(IPage<WxReplyRuleVO> page, Map<String, Object> params) {
        return page.setRecords(baseMapper.selectWxReplyRulePage(page, params));
    }

    /**
	 * 自定义Wrappers
	 */
    public QueryWrapper<WxReplyRule> selectWxReplyRuleWrapper(Map<String, Object> params) {
        QueryWrapper<WxReplyRule> wrapper = Wrappers.query();
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("type")), WxReplyRule::getType, params.get("type"));
        wrapper.lambda().like(ObjectUtil.isNotEmpty(params.get("name")), WxReplyRule::getName, params.get("name"));
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("status")), WxReplyRule::getStatus, params.get("status"));
        wrapper.lambda().orderByDesc(WxReplyRule::getSort).orderByDesc(WxReplyRule::getId);
        return wrapper;
    }


	/**
	 * 根据规则配置通过微信客服消息接口自动回复消息
	 * @param toUser     用户openid
	 * @param keywords   匹配关键词
	 * @return 是否已自动回复，无匹配规则则不自动回复
	 */
	public boolean tryAutoReply(String toUser, String keywords) {
		//先进行关键词匹配
		WxReplyRule wxReplyRule = null;
		List<WxReplyRule> wxReplyRuleList = baseMapper.selectList(Wrappers.<WxReplyRule>lambdaQuery().eq(WxReplyRule::getType, 3).eq(WxReplyRule::getStatus, 1).orderByDesc(WxReplyRule::getSort));
		for(WxReplyRule wxReplyRule1 : wxReplyRuleList){
			if(isMatch(wxReplyRule1.getMatchType() == 1, wxReplyRule1.getMatchValue().split(","), keywords)){
				wxReplyRule = wxReplyRule1;
			}
		}

		//无效关键词匹配
		if(ObjectUtil.isEmpty(wxReplyRule)){
			wxReplyRule = baseMapper.selectOne(Wrappers.<WxReplyRule>lambdaQuery().eq(WxReplyRule::getType, 2).eq(WxReplyRule::getStatus, 1).orderByDesc(WxReplyRule::getSort).last("limit 1"));
		}
		if(ObjectUtil.isNotEmpty(wxReplyRule)){
			reply(toUser, wxReplyRule.getReplyType(), wxReplyRule.getReplyValue());
			return true;
		}
		return false;
	}

	/**
	 * 检测文字是否匹配规则
	 * 精确匹配时，需关键词与规则词语一致
	 * 非精确匹配时，检测文字需包含任意一个规则词语
	 *
	 * @param exactMatch 是否精确匹配
	 * @param ruleWords  规则列表
	 * @param checkWords 需检测的文字
	 * @return
	 */
	public boolean isMatch(boolean exactMatch, String[] ruleWords, String checkWords) {
		if (!StringUtils.hasText(checkWords)) {
			return false;
		}
		for (String words : ruleWords) {
			if (exactMatch && words.equals(checkWords)) {
				return true;//精确匹配，需关键词与规则词语一致
			}
			if (!exactMatch && checkWords.contains(words)) {
				return true;//模糊匹配
			}
		}
		return false;
	}


	/**
	 * 发送客服消息
	 * @param toUser 用户openid
	 * @param replyType 回复类型
	 * @param replyContent 回复类容
	 */
	public void reply(String toUser,String replyType, String replyContent){
		try {
			if (WxConsts.KefuMsgType.TEXT.equals(replyType)) {
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT().toUser(toUser).content(replyContent).build());
			} else if (WxConsts.KefuMsgType.IMAGE.equals(replyType)) {
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.IMAGE().toUser(toUser).mediaId(replyContent).build());
			} else if (WxConsts.KefuMsgType.VOICE.equals(replyType)) {
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.VOICE().toUser(toUser).mediaId(replyContent).build());
			} else if (WxConsts.KefuMsgType.VIDEO.equals(replyType)) {
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.VIDEO().toUser(toUser).mediaId(replyContent).build());
			} else if (WxConsts.KefuMsgType.MP_NEWS_ARTICLE.equals(replyType)) {
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.MPNEWSARTICLE().toUser(toUser).articleId(replyContent).build());
			}
		} catch (WxErrorException e) {
			log.error(StringUtil.format("发送客服消息错误码：{}， 错误信息{}", e.getError().getErrorCode(), e.getError().getErrorMsg()));
		}
	}

}

